package com.example.activities;

import java.util.ArrayList;
import java.util.List;

import com.example.demo.R;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.os.Build;

public class AsyncTaskPage extends ActionBarActivity {
	List<Integer> listAsync;
	ListView lvAsync;
	ArrayAdapter<Integer> dataAsync;
	ProgressBar proAsync;
	TextView txtLoading;

	private int mCurrentPage = 0;
	private int mPreviousTotal = 0;
	private int savePos = 0;
	private boolean mLoading = true;
	private boolean mLastPage = false;
	private static int DATA_UNIT = 15;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_async_task);

		listAsync = new ArrayList<Integer>();
		lvAsync = (ListView) findViewById(R.id.lvAsync);
		proAsync = (ProgressBar) findViewById(R.id.progressBar1);
		txtLoading = (TextView) findViewById(R.id.txtLoading);
		proAsync.setVisibility(View.GONE);
		for (int i = 0; i < DATA_UNIT; i++) {
			listAsync.add(i + 1);
		}

		dataAsync = new ArrayAdapter<Integer>(AsyncTaskPage.this,
				android.R.layout.simple_dropdown_item_1line, listAsync);
		lvAsync.setAdapter(dataAsync);
		lvAsync.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				if (mLoading) {
					Log.d("totalItemCount:", "" + totalItemCount);
					Log.d("mPreviousTotal:", "" + mPreviousTotal);
					if (totalItemCount >= mPreviousTotal) {
						savePos = lvAsync.getFirstVisiblePosition();
						mLoading = false;
						mPreviousTotal = totalItemCount;
						mCurrentPage++;
						// Find your own condition in order to know when you
						// have finished displaying all items
						if (mCurrentPage * DATA_UNIT >= 400) {
							mLastPage = true;
						}
					}
				}
				if (!mLoading
						&& (totalItemCount - visibleItemCount) <= (firstVisibleItem)) {
					new LoadMoreData().execute();
					mLoading = true;
				}

			}
		});

		if (savedInstanceState == null) {
			getSupportFragmentManager().beginTransaction()
					.add(R.id.container, new PlaceholderFragment()).commit();
		}
	}

	class LoadMoreData extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			txtLoading.setText("Loading more data using AsyncTask");
			proAsync.setVisibility(View.VISIBLE);
		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					for (int j = 0; j < 1; j++) {
						doFakeWork();
					}
					for (int i = mCurrentPage * DATA_UNIT; i < (mCurrentPage + 1)
							* DATA_UNIT; i++) {
						if (i <= 420) {
							listAsync.add(i + 1);
						}
						dataAsync = new ArrayAdapter<Integer>(
								AsyncTaskPage.this,
								android.R.layout.simple_dropdown_item_1line,
								listAsync);
						dataAsync.notifyDataSetChanged();
						lvAsync.setAdapter(dataAsync);
					}
				}
			});
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			txtLoading.setText("");
			proAsync.setVisibility(View.GONE);
		}
	}

	private void doFakeWork() {
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.async_task, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment {

		public PlaceholderFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_async_task,
					container, false);
			return rootView;
		}
	}

}
